import 'package:flutter/material.dart';
import 'package:schoollifedemo/business/school/viewmodel/memorandum_select_all_page_viewmodel.dart';
import 'package:schoollifedemo/commonwidget/circle_empty_widget.dart';
import 'package:schoollifedemo/commonwidget/common_base_page.dart';
import 'package:schoollifedemo/commonwidget/common_dialog.dart';
import 'package:schoollifedemo/commonwidget/error_widget.dart';
import 'package:schoollifedemo/commonwidget/loading_widget.dart';
import 'package:schoollifedemo/commonwidget/text_widget_with_overflow.dart';
import 'package:schoollifedemo/entity/Entity.dart';

// 查看所有备忘录页面
class SelectAllMemorandumPage extends BaseStatefulPage {
  const SelectAllMemorandumPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _SelectAllMemorandumPageState();
  }
}

class _SelectAllMemorandumPageState
    extends BasePageState<SelectAllMemorandumPage> {
  final MemorandumSelectAllPageViewModel _viewModel =
      MemorandumSelectAllPageViewModel();
  bool _isEditMode = false;
  bool _selectAll = false;

  @override
  void initState() {
    _viewModel.init();
    _viewModel.pullUserMemorandumList();
    super.initState();
  }

  @override
  void dispose() {
    _viewModel.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
        color: Colors.white,
        child: Column(
          children: [
            Row(
              children: [
                GestureDetector(
                  onTap: () {
                    _viewModel.backPage(context);
                  },
                  child: Container(
                    margin: const EdgeInsets.only(left: 20),
                    child: const Icon(Icons.arrow_back_ios_outlined),
                  ),
                ),
                const Expanded(
                  child: TextWidgetWithOverflow(
                    '备忘录',
                    fontSize: 28,
                    insideColor: Colors.transparent,
                    textAlign: TextAlign.left,
                  ),
                ),
                Offstage(
                  offstage:
                      _viewModel.userMemorandumResp?.memorandumList?.isEmpty ==
                          true,
                  child: Offstage(
                    offstage: _isEditMode,
                    child: GestureDetector(
                      onTap: () async {
                        // 返回操作
                        _viewModel.changeAllUnSelect();
                        _isEditMode = !_isEditMode;
                        setState(() {});
                      },
                      child: Container(
                        margin: const EdgeInsets.only(right: 20),
                        child: const TextWidgetWithOverflow(
                          '编辑',
                          fontSize: 14,
                          width: 50,
                        ),
                      ),
                    ),
                  ),
                ),
                Offstage(
                  offstage: _isEditMode,
                  child: GestureDetector(
                    onTap: () async {
                      await _viewModel.turnToEditMemorandumPage(
                        context,
                        isEditMode: true,
                      );
                      _viewModel.pullUserMemorandumList(
                        refreshQuickly: true,
                        onSuccess: () {
                          setState(() {});
                        },
                      );
                    },
                    child: Container(
                      margin: const EdgeInsets.only(right: 20),
                      child: const Icon(Icons.add),
                    ),
                  ),
                ),
                Offstage(
                  offstage: _viewModel.deleteList.isEmpty,
                  child: GestureDetector(
                    onTap: () async {
                      // delete all
                      bool? trueOrFalse =
                          await DialogUtils.showCancelAndConfirmDialog(
                        context,
                        title: '提示',
                        msg: '已编辑，是否取消修改?',
                      );
                      if (trueOrFalse == true) {
                        _isEditMode = false;
                        _viewModel.deleteList.clear();

                        await _viewModel.deleteAllMemorandumFromList(
                          onFailure: (msg) {
                            DialogUtils.showTitleAndMessageDialog(
                              context,
                              title: '错误',
                              msg: msg,
                            );
                          },
                        );
                        _viewModel.pullUserMemorandumList(
                          refreshQuickly: true,
                          onSuccess: () {
                            setState(() {});
                          },
                        );
                      }
                    },
                    child: Container(
                      margin: const EdgeInsets.only(right: 10),
                      child: const Icon(Icons.delete_forever),
                    ),
                  ),
                ),
                Offstage(
                  offstage: !_isEditMode,
                  child: GestureDetector(
                    onTap: () async {
                      _selectAll = !_selectAll;
                      if (_selectAll) {
                        // 全选
                        _viewModel.changeAllSelect();
                      } else {
                        // 非全选
                        _viewModel.changeAllUnSelect();
                      }
                      setState(() {});
                    },
                    child: Container(
                      margin: const EdgeInsets.only(right: 5),
                      child: TextWidgetWithOverflow(
                        _selectAll ? '取消' : '全选',
                        fontSize: 14,
                        width: 50,
                      ),
                    ),
                  ),
                ),
                Offstage(
                  offstage: !_isEditMode,
                  child: GestureDetector(
                    onTap: () async {
                      // 返回操作
                      _viewModel.deleteList.clear();
                      _isEditMode = !_isEditMode;
                      setState(() {});
                    },
                    child: Container(
                      margin: const EdgeInsets.only(right: 20),
                      child: const TextWidgetWithOverflow(
                        '返回',
                        fontSize: 14,
                        width: 50,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            StreamBuilder(
              stream: _viewModel.memorandumLoadingState,
              initialData: CommonLoadingState.loading,
              builder: (buildContext, snapshot) {
                final loadingState = snapshot.data as CommonLoadingState?;
                switch (loadingState) {
                  case CommonLoadingState.loading:
                    return Expanded(child: _loadingWidget());
                  case CommonLoadingState.successTypeOne:
                  case CommonLoadingState.successTypeTwo:
                    return Expanded(child: _commonBody());
                  default:
                    return Expanded(child: _errorWidget());
                }
              },
            )
          ],
        ),
      ),
    );
  }

  Widget _emptyWidget() {
    return Column(
      children: [
        Center(
          child: Container(
            width: 200,
            height: 200,
            margin: const EdgeInsets.only(top: 30, bottom: 50),
            child: Image.asset('assets/images/school/img_empty_memorandum.png'),
          ),
        ),
        GestureDetector(
          onTap: () async {
            await _viewModel.turnToEditMemorandumPage(context);
            _viewModel.pullUserMemorandumList(
              refreshQuickly: true,
              onSuccess: () {
                setState(() {});
              },
            );
          },
          child: const TextWidgetWithOverflow(
            '写一条备忘录？',
            fontSize: 16,
          ),
        ),
      ],
    );
  }

  Widget _errorWidget() {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: CommonErrorWidget(
          '错误重试',
          onButtonClick: () async {
            _viewModel.pullUserMemorandumList(
              refreshQuickly: true,
              onSuccess: () {
                setState(() {});
              },
              onFailure: (msg) {
                DialogUtils.showTitleAndMessageDialog(
                  context,
                  title: '错误',
                  msg: msg,
                );
              },
            );
          },
        ),
      ),
    );
  }

  Widget _loadingWidget() {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: const LoadingWidget(),
      ),
    );
  }

  Widget _commonBody() {
    return RefreshIndicator(
      onRefresh: () async {
        // refresh
        _viewModel.pullUserMemorandumList(
            refreshQuickly: true,
            onSuccess: () {
              setState(() {});
            });
      },
      child: ListView(
        physics: const BouncingScrollPhysics(),
        children: [
          Container(
            margin: const EdgeInsets.only(
              left: 20,
              right: 20,
              bottom: 20,
            ),
            child: ListView.separated(
              physics: const NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemBuilder: (buildContext, index) {
                final item =
                    _viewModel.userMemorandumResp?.memorandumList?[index];
                return GestureDetector(
                  onTapUp: (details) async {
                    // 短按事件
                    if (_isEditMode) {
                      if (item?.isSelect == true) {
                        item?.isSelect = false;
                        _viewModel.deleteList.remove(item?.noteId);
                      } else {
                        item?.isSelect = true;
                        _viewModel.deleteList.add(item?.noteId);
                      }
                      if (_viewModel.checkSelectAll()) {
                        _selectAll = true;
                      } else {
                        _selectAll = false;
                      }
                    } else {
                      await _viewModel.turnToEditMemorandumPage(context,
                          noteId: item?.noteId, isEditMode: false);
                      _viewModel.pullUserMemorandumList(
                        refreshQuickly: true,
                        onSuccess: () {
                          setState(() {});
                        },
                      );
                    }
                    setState(() {});
                  },
                  child: Row(
                    children: [
                      Expanded(
                        child: Container(
                          child: _memorandumItemWidget(
                            title: item?.title ?? '',
                            msg: item?.msg ?? '',
                            lastEditTime: item?.lastEditTime ?? '',
                            widgetColor:
                                item?.defaultColor ?? const Color(0x66B8DCFF),
                          ),
                        ),
                      ),
                      Offstage(
                        offstage: !_isEditMode,
                        child: Container(
                          margin: const EdgeInsets.only(right: 10),
                          child: item?.isSelect == true
                              ? const Icon(Icons.check_circle_outline)
                              : const Icon(Icons.radio_button_unchecked),
                        ),
                      )
                    ],
                  ),
                );
              },
              separatorBuilder: (buildContext, index) {
                return Container(
                  height: 10,
                );
              },
              itemCount:
                  _viewModel.userMemorandumResp?.memorandumList?.length ?? 0,
            ),
          ),
          Offstage(
            offstage:
                _viewModel.userMemorandumResp?.memorandumList?.isEmpty == false,
            child: _emptyWidget(),
          ),
        ],
      ),
    );
  }

  // 备忘录子项
  Widget _memorandumItemWidget({
    required String title,
    required String msg,
    required String lastEditTime,
    required Color widgetColor,
  }) {
    return CircleEmptyWidget(
      Container(
        margin: const EdgeInsets.all(10),
        child: IntrinsicHeight(
          child: Column(
            children: [
              TextWidgetWithOverflow(
                title,
                fontSize: 20,
                insideColor: Colors.transparent,
                textAlign: TextAlign.left,
                width: double.infinity,
              ),
              TextWidgetWithOverflow(
                '${_viewModel.getLastEditTime(time: lastEditTime)} ',
                fontSize: 12,
                insideColor: Colors.transparent,
                textAlign: TextAlign.left,
                width: double.infinity,
              ),
            ],
          ),
        ),
      ),
      insideColor: widgetColor,
    );
  }
}
